# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html


# useful for handling different item types with a single interface
from itemadapter import ItemAdapter
from bid.settings import MySQInit
import pymysql
class MysqlPipeline(object):
    def open_spider(self, spider):
        try:
            self.conn = pymysql.connect(host=MySQInit['host'], port=MySQInit['port'], user=MySQInit['user'], passwd=MySQInit['password'], db=MySQInit['db'],
                                        charset=MySQInit['charset'])
            print('MySQL初始化成功')
        except Exception as e:
            print(f'MySQL连接失败：{e}')
            exit()
    def process_item(self, item, spider):
        self.cursor = self.conn.cursor()
        try:
            col = ','.join(item.keys())
            val = str(tuple(item.values()))
            sql = f'INSERT INTO {MySQInit["table"]} ({col}) VALUES {val}'
            self.cursor.execute(sql)
            print(f'MySQL写入>>{item["link"]}')
            self.conn.commit()
        except Exception as e:
            print(f"MySQL存储失败>>{item['linke']}>>{e}")
            self.conn.rollback()
        return item
    def close_spider(self, spider):
        self.cursor.close()
        self.conn.close()
        print('MySQL断开链接')

from bid.settings import ElasticsearchInit
from elasticsearch import Elasticsearch
from bid.tools import md5_encrypt
class ElasticsearchPipeline(object):
    def open_spider(self, spider):
        if ElasticsearchInit['host'] and ElasticsearchInit['http_auth']:
            self.es = Elasticsearch(hosts=ElasticsearchInit['host'],http_auth=ElasticsearchInit['http_auth'])
        elif ElasticsearchInit['host']:
            self.es = Elasticsearch(hosts=ElasticsearchInit['host'])
        else:
            self.es = Elasticsearch()
        print('Elasticsearch初始化成功')
    def process_item(self, item, spider):
        if item['content']=='':
            return
        self.es.index(index=ElasticsearchInit['index'],body=dict(item))
        print(f'Elasticsearch写入>>')
        return item
    def close_spider(self, spider):
        self.es.close()
        print('Elasticsearch断开链接')

from bid.settings import MongoDBInit
import pymongo
class MongoDBPipeline(object):
    def open_spider(self, spider):
        if MongoDBInit['auth']:
            self.mongo = pymongo.MongoClient(host=MongoDBInit['host'],port=MongoDBInit['port'],username=MongoDBInit['auth']['username'], password=MongoDBInit['auth']['password'])
        else:
            self.mongo = pymongo.MongoClient(host=MongoDBInit['host'], port=MongoDBInit['port'])
        self.col = self.mongo[MongoDBInit['db']][MongoDBInit['col']]
        print('MongoDB初始化成功')
    def process_item(self, item, spider):
        self.col.insert_one(dict(item))
        print(f'MongoDB写入>>')
        return item
    def close_spider(self, spider):
        self.mongo.close()
        print('MongoDB断开链接')

